import { useState, useEffect, useMemo, useCallback } from 'react';
import { message, Form } from 'antd';
import type { DataNode } from 'antd/es/tree';
import { roleApi } from '../../services/cloud/api/roleApi';
import type { RoleWithUserCount, CreateRoleRequest, UpdateRoleRequest, AssignPermissionsRequest } from '../../services/cloud/api/roleApi';
import type { Role } from '../../types/rbac';

// 角色类型定义 - 使用后端API的类型
interface RoleInternal extends RoleWithUserCount {
  permissions: string[];
  // 添加后端SysRole实体的字段映射
  roleName: string;
  roleKey: string;
  remark?: string;
}

// 角色表单数据接口
interface RoleFormData {
  roleName: string;
  roleKey: string;
  remark?: string;
  permissions: string[];
  status: 'active' | 'disabled'; // 使用StatusEnum的字符串代码
}

// 角色查询参数类型
interface RoleQueryParams {
  search?: string;
  status?: string;
}

/**
 * 角色管理统一hooks
 * 整合了角色列表、详情、表单、权限分配、树构建等所有功能
 */
export const useRoles = (params?: RoleQueryParams) => {
  // ==================== 基础状态管理 ====================
  const [roles, setRoles] = useState<RoleInternal[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState(params?.search || '');
  
  // ==================== 角色详情状态 ====================
  const [viewingRole, setViewingRole] = useState<Role | null>(null);
  const [viewingRoleMenus, setViewingRoleMenus] = useState<string[]>([]);
  const [viewingRolePermissions, setViewingRolePermissions] = useState<string[]>([]);
  const [detailsVisible, setDetailsVisible] = useState(false);
  const [detailsLoading, setDetailsLoading] = useState(false);
  
  // ==================== 表单管理状态 ====================
  const [modalVisible, setModalVisible] = useState(false);
  const [editingRole, setEditingRole] = useState<Role | null>(null);
  const [form] = Form.useForm();
  
  // ==================== 权限分配状态 ====================
  const [permissionEditingRole, setPermissionEditingRole] = useState<Role | null>(null);
  const [permissionModalVisible, setPermissionModalVisible] = useState(false);
  const [selectedPermissions, setSelectedPermissions] = useState<string[]>([]);
  const [selectedMenus, setSelectedMenus] = useState<string[]>([]);
  const [activeTab, setActiveTab] = useState('menus');
  const [permissionLoading, setPermissionLoading] = useState(false);
  
  // ==================== 权限树状态 ====================
  const [permissionTree, setPermissionTree] = useState<any[]>([]);
  const [permissionTreeLoading, setPermissionTreeLoading] = useState(false);

  // ==================== 基础数据加载方法 ====================
  const loadRoles = async () => {
    try {
      setLoading(true);
      
      // 构建查询参数
      const queryParams = {
        page: 1,
        size: 1000, // 获取所有数据
        name: searchText,
        status: params?.status === 'all' ? undefined : params?.status as 'active' | 'inactive',
      };
      
      const response = await roleApi.getRoles(queryParams);
      console.log('角色API响应:', response); // 调试日志
      
      // 处理API响应，根据RoleListResponse类型定义
      let rolesData: any[] = [];
      if (response && response.records && Array.isArray(response.records)) {
        // 标准分页响应格式: { records: [], totalElements: 0 }
        rolesData = response.records;
      } else if (response && Array.isArray(response)) {
        // 直接数组格式: []
        rolesData = response;
      } else {
        console.warn('角色API响应格式异常:', response);
        rolesData = [];
      }
      

      const rolesWithPermissions = rolesData.map(role => ({
        ...role,
        permissions: [], // 权限需要单独获取
        // 字段映射：后端字段 -> 前端字段
        id: role.id || role.roleId,
        roleName: role.name || role.roleName || '',
        roleKey: role.code || role.roleKey || '',
        remark: role.description || role.remark || '',
        status: role.status || '1',
        createTime: role.createTime || role.createdAt,
        updateTime: role.updateTime || role.updatedAt,
        userCount: role.userCount || 0,
      }));
      
      console.log('映射后的角色数据:', rolesWithPermissions); // 调试日志
      setRoles(rolesWithPermissions);
    } catch (error) {
      console.error('加载角色列表失败:', error);
      message.error('加载角色列表失败');
      setRoles([]); // 确保在错误时设置空数组
    } finally {
      setLoading(false);
    }
  };
  
  // 加载权限树数据
  const loadPermissionTree = async () => {
    try {
      setPermissionTreeLoading(true);
      // 直接导入permissionApi
      const { permissionApi } = await import('../../services/cloud/api/permissionApi');
      const tree = await permissionApi.getPermissionTree();
      console.log('获取到的权限树数据:', tree);
      setPermissionTree(tree || []);
      return tree || [];
    } catch (error) {
      console.error('获取权限树失败:', error);
      message.error('获取权限树失败');
      setPermissionTree([]);
      return [];
    } finally {
      setPermissionTreeLoading(false);
    }
  };
  
  // 过滤角色数据
  const filteredRoles = useMemo(() => {
    if (!searchText) return roles;
    return roles.filter(role => {
      return (
        role.roleName.toLowerCase().includes(searchText.toLowerCase()) ||
        role.roleKey.toLowerCase().includes(searchText.toLowerCase()) ||
        (role.remark && role.remark.toLowerCase().includes(searchText.toLowerCase()))
      );
    });
  }, [roles, searchText]);

  useEffect(() => {
    loadRoles();
    loadPermissionTree();
  }, [searchText, params?.status]);
  
  // ==================== 权限相关工具方法 ====================
  const fetchPermissions = useCallback(async (roleId: string) => {
    try {
      const permissionCodes = await roleApi.getRolePermissions(roleId);
      return permissionCodes || [];
    } catch (error) {
      console.error('获取角色权限失败:', error);
      message.error('获取角色权限失败');
      return [];
    }
  }, []);
  
  // ==================== 树构建工具方法 ====================
  const buildPermissionTree = useCallback((permissionTreeData: any[]): DataNode[] => {
    if (!permissionTreeData || permissionTreeData.length === 0) {
      return [];
    }
    
    const convertToTreeData = (nodes: any[]): DataNode[] => {
      return nodes.map(node => ({
        title: node.name || node.title || '未命名权限',
        key: String(node.id || node.key || Math.random()),
        children: node.children && node.children.length > 0 
          ? convertToTreeData(node.children) 
          : undefined,
      }));
    };
    
    return convertToTreeData(permissionTreeData);
  }, []);

  const buildMenuTree = useCallback((menuTreeData: any[]): DataNode[] => {
    if (!menuTreeData || menuTreeData.length === 0) {
      return [];
    }
    
    const convertToTreeData = (nodes: any[]): DataNode[] => {
      return nodes.map(node => ({
        title: node.name || node.title || '未命名菜单',
        key: String(node.id || node.key || Math.random()),
        children: node.children && node.children.length > 0 
          ? convertToTreeData(node.children) 
          : undefined,
      }));
    };
    
    return convertToTreeData(menuTreeData);
  }, []);

  const getMenuName = useCallback((menuId: string, menuTreeData: any[]): string => {
    const findMenu = (nodes: any[]): string | null => {
      for (const node of nodes) {
        if (String(node.id) === menuId) {
          return node.name;
        }
        if (node.children) {
          const found = findMenu(node.children);
          if (found) return found;
        }
      }
      return null;
    };
    
    return findMenu(menuTreeData) || `菜单ID-${menuId}`;
  }, []);

  const getPermissionNameByCode = useCallback((permissionCode: string, permissionTreeData: any[]): string => {
    const findPermission = (nodes: any[]): string | null => {
      for (const node of nodes) {
        if (node.code === permissionCode) {
          return node.name;
        }
        if (node.children) {
          const found = findPermission(node.children);
          if (found) return found;
        }
      }
      return null;
    };
    
    return findPermission(permissionTreeData) || `权限代码-${permissionCode}`;
  }, []);
  
  // ==================== 辅助工具方法 ====================
  const getIsRoleActive = useCallback((status: string | number): boolean => {
    // 支持StatusEnum的字符串格式和数字格式
    if (typeof status === 'string') {
      return status === 'active' || status === '1';
    } else {
      return status === 1; // 后端返回1表示启用，0表示禁用
    }
  }, []);

  const getToggleStatus = useCallback((status: string | number): 'active' | 'disabled' => {
    if (typeof status === 'string') {
      return (status === 'active' || status === '1') ? 'disabled' : 'active';
    } else {
      return status === 1 ? 'disabled' : 'active'; // 后端返回1表示启用，0表示禁用
    }
  }, []);

  const getStatusText = useCallback((status: string | number): string => {
    return getIsRoleActive(status) ? '启用' : '禁用';
  }, [getIsRoleActive]);

  const getStatusColor = useCallback((status: string | number): string => {
    return getIsRoleActive(status) ? 'success' : 'default'; // 使用success绿色表示启用状态
  }, [getIsRoleActive]);

  const formatDateTime = useCallback((dateTime?: string | Date): string => {
    if (!dateTime) return '暂无';
    try {
      return new Date(dateTime).toLocaleString();
    } catch (error) {
      console.error('时间格式化失败:', error);
      return '暂无';
    }
  }, []);
  
  // ==================== 角色操作方法 ====================
  const createRole = async (data: RoleFormData) => {
    try {
      setLoading(true);
      
      const createData: CreateRoleRequest = {
        name: data.roleName,
        code: data.roleKey,
        description: data.remark,
        permissions: data.permissions,
        status: data.status, // 直接使用StatusEnum字符串代码
      };
      
      const newRole = await roleApi.createRole(createData);
      message.success('角色创建成功');
      return newRole;
    } catch (error) {
      console.error('角色创建失败:', error);
      message.error('角色创建失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const updateRole = async (id: string, data: Partial<RoleFormData>) => {
    try {
      setLoading(true);
      
      const updateData: UpdateRoleRequest = {
        name: data.roleName,
        code: data.roleKey,
        description: data.remark,
        permissions: data.permissions,
        status: data.status, // 直接使用StatusEnum字符串代码
      };
      
      const updatedRole = await roleApi.updateRole(id, updateData);
      message.success('角色更新成功');
      return updatedRole;
    } catch (error) {
      console.error('角色更新失败:', error);
      message.error('角色更新失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const deleteRole = async (id: string) => {
    try {
      setLoading(true);
      await roleApi.deleteRole(id);
      message.success('角色删除成功');
    } catch (error) {
      console.error('角色删除失败:', error);
      message.error('角色删除失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const assignPermissions = async (roleId: string, permissions: string[]) => {
    try {
      setLoading(true);
      const data: AssignPermissionsRequest = {
        roleId,
        permissions,
      };
      await roleApi.assignPermissions(data);
      message.success('权限分配成功');
    } catch (error) {
      console.error('权限分配失败:', error);
      message.error('权限分配失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  // 切换角色状态
  const toggleStatus = async (id: string, status: 'active' | 'disabled') => {
    try {
      setLoading(true);
      await roleApi.toggleRoleStatus(id, status);
      message.success(`角色${status === 'active' ? '启用' : '禁用'}成功`);
      await loadRoles(); // 重新获取角色列表
    } catch (error) {
      console.error('切换角色状态失败:', error);
      message.error(`角色${status === 'active' ? '启用' : '禁用'}失败`);
    } finally {
      setLoading(false);
    }
  };

  return {
    // 基础数据
    roles,
    loading,
    refresh: loadRoles,
    searchText,
    setSearchText,
    filteredRoles,
    
    // 权限树数据
    permissionTree,
    permissionTreeLoading,
    
    // 工具方法
    buildPermissionTree,
    buildMenuTree,
    getMenuName,
    getPermissionNameByCode,
    getIsRoleActive,
    getToggleStatus,
    getStatusText,
    getStatusColor,
    formatDateTime,
    
    // 角色操作方法
    createRole,
    updateRole,
    deleteRole,
    assignPermissions,
    toggleStatus,
    
    // ==================== 角色详情相关方法 ====================
    // 详情状态
    viewingRole,
    viewingRoleMenus,
    viewingRolePermissions,
    detailsVisible,
    detailsLoading,
    
    // 详情操作方法
    openRoleDetails: useCallback(async (role: Role) => {
      setViewingRole(role);
      setDetailsVisible(true);
      setDetailsLoading(true);
      
      try {
        const [menuIds, permissions] = await Promise.all([
          roleApi.getRoleMenus(role.id.toString()),
          fetchPermissions(role.id)
        ]);
        
        const menuIdStrings = Array.isArray(menuIds) ? menuIds.map(String) : [];
        setViewingRoleMenus(menuIdStrings);
        setViewingRolePermissions(permissions || []);
        
        console.log('角色详情数据加载完成:', {
          roleId: role.id,
          menusCount: menuIdStrings.length,
          permissionsCount: (permissions || []).length
        });
      } catch (error) {
        console.error('获取角色详情失败:', error);
        message.error('获取角色详情失败');
        setViewingRoleMenus([]);
        setViewingRolePermissions([]);
      } finally {
        setDetailsLoading(false);
      }
    }, [fetchPermissions]),
    
    closeRoleDetails: useCallback(() => {
      setDetailsVisible(false);
      setViewingRole(null);
      setViewingRoleMenus([]);
      setViewingRolePermissions([]);
    }, []),
    
    // ==================== 表单管理相关方法 ====================
    // 表单状态
    modalVisible,
    editingRole,
    form,
    
    // 表单操作方法
    openAddForm: useCallback(() => {
      setEditingRole(null);
      setModalVisible(true);
      form.resetFields();
    }, [form]),
    
    openEditForm: useCallback((role: Role) => {
      setEditingRole(role);
      setModalVisible(true);
      form.setFieldsValue({
        roleName: role.roleName,
        roleKey: role.roleKey,
        remark: role.remark,
        status: (role.status === 1 || role.status === 'active') ? '0' : '1',
      });
    }, [form]),
    
    closeForm: useCallback(() => {
      setModalVisible(false);
      form.resetFields();
      setEditingRole(null);
    }, [form]),
    
    submitForm: useCallback(async (values: any, onSuccess?: () => void) => {
      try {
        const roleData = {
          ...values,
          permissions: editingRole?.permissions || [],
        };
        
        if (editingRole) {
          await updateRole(editingRole.id, roleData);
        } else {
          await createRole(roleData);
        }
        
        setModalVisible(false);
        form.resetFields();
        onSuccess?.();
      } catch (error) {
        console.error('角色操作失败:', error);
      }
    }, [editingRole, form, createRole, updateRole]),
    
    // ==================== 权限分配相关方法 ====================
    // 权限分配状态
    permissionEditingRole,
    permissionModalVisible,
    selectedPermissions,
    selectedMenus,
    activeTab,
    permissionLoading,
    setSelectedPermissions,
    setSelectedMenus,
    setActiveTab,
    
    // 权限分配操作方法
    openPermissionAssignment: useCallback(async (role: Role, permissionTreeData: any[]) => {
      setPermissionEditingRole(role);
      setActiveTab('menus');
      setPermissionModalVisible(true);
      setPermissionLoading(true);
      
      setSelectedPermissions([]);
      setSelectedMenus([]);
      
      try {
        const [permissionsResult, menuIdsResult] = await Promise.all([
          fetchPermissions(role.id),
          roleApi.getRoleMenus(role.id.toString())
        ]);
        
        // 权限代码转换为权限ID
        const convertPermissionCodesToIds = (codes: string[]): string[] => {
          const ids: string[] = [];
          const findPermissionId = (nodes: any[], code: string): string | null => {
            for (const node of nodes) {
              if (node.code === code) return String(node.id);
              if (node.children) {
                const found = findPermissionId(node.children, code);
                if (found) return found;
              }
            }
            return null;
          };
          
          codes.forEach(code => {
            const id = findPermissionId(permissionTreeData, code);
            if (id) {
              ids.push(id);
            } else if (/^\d+$/.test(code)) {
              ids.push(code);
            }
          });
          
          return ids;
        };
        
        const rolePermissionIds = convertPermissionCodesToIds(permissionsResult || []);
        const roleMenuIds = Array.isArray(menuIdsResult) ? menuIdsResult.map(String) : [];
        
        setSelectedPermissions(rolePermissionIds);
        setSelectedMenus(roleMenuIds);
        
        console.log('权限分配弹框数据加载完成:', {
          roleId: role.id,
          permissionsCount: rolePermissionIds.length,
          menusCount: roleMenuIds.length
        });
      } catch (error) {
        console.error('获取角色权限失败:', error);
        message.error('获取角色权限失败');
        setSelectedPermissions([]);
        setSelectedMenus([]);
      } finally {
        setPermissionLoading(false);
      }
    }, [fetchPermissions]),
    
    closePermissionAssignment: useCallback(() => {
      setPermissionModalVisible(false);
      setPermissionEditingRole(null);
      setSelectedPermissions([]);
      setSelectedMenus([]);
    }, []),
    
    submitPermissionAssignment: useCallback(async (permissionTreeData: any[], onSuccess?: () => void) => {
      if (!permissionEditingRole) return;
      
      try {
        if (activeTab === 'menus') {
          await roleApi.assignMenusToRole(permissionEditingRole.id.toString(), selectedMenus);
          message.success('菜单权限分配成功');
        } else {
          // 权限ID转换为权限代码
          const convertPermissionIdsToCodes = (ids: string[]): string[] => {
            const codes: string[] = [];
            const findPermissionCode = (nodes: any[], id: string): string | null => {
              for (const node of nodes) {
                if (String(node.id) === id) return node.code;
                if (node.children) {
                  const found = findPermissionCode(node.children, id);
                  if (found) return found;
                }
              }
              return null;
            };
            
            ids.forEach(id => {
              const code = findPermissionCode(permissionTreeData, id);
              codes.push(code || id);
            });
            
            return codes;
          };
          
          const permissionCodes = convertPermissionIdsToCodes(selectedPermissions);
          await assignPermissions(permissionEditingRole.id, permissionCodes);
          message.success('功能权限分配成功');
        }
        setPermissionModalVisible(false);
        onSuccess?.();
      } catch (error) {
        console.error('权限分配失败:', error);
        message.error('权限分配失败');
      }
    }, [permissionEditingRole, activeTab, selectedMenus, selectedPermissions, assignPermissions]),
  };
};

// 角色操作管理hook（兼容性保持）
export const useRoleActions = () => {
  const roleHook = useRoles();
  return {
    loading: roleHook.loading,
    createRole: roleHook.createRole,
    updateRole: roleHook.updateRole,
    deleteRole: roleHook.deleteRole,
    assignPermissions: roleHook.assignPermissions,
    toggleStatus: roleHook.toggleStatus,
  };
};

// 权限树管理hook（兼容性保持）
export const useRolePermissionTree = () => {
  const roleHook = useRoles();
  return {
    permissionTree: roleHook.permissionTree,
    loading: roleHook.permissionTreeLoading,
  };
};

// 导出类型
export type { 
  RoleInternal as Role, 
  RoleFormData, 
  RoleQueryParams,
  CreateRoleRequest,
  UpdateRoleRequest,
  AssignPermissionsRequest
};